Reversing an Array

In this recipe we find out that JavaScript in Navigator can reverse arrays for us.

Fill in the top row of boxes and press the "GO!" button.

Original:

Reversed:

Discussion

Everything you need to know about this capability can be summed up in two code fragments. Which would you rather write?

The Hard Way

function Reverse(anArray)
{
	var len	= anArray.length;
	var tempArray = new Array(len); 
	var i;
	var j = len - 1 ;
	for(i = 0; i < len; i++) {
		tempArray[i] = anArray[j];
		j -= 1;
	}
	return tempArray;	
}

The Easy Way

anArray.reverse();
Perhaps we've tried to sway you by calling one the hard way and one the easy way, but we think we'll get little argument that letting the JavaScript engine do it is the preferred method.


Copyright ©1998 by Charles River Media, All Rights Reserved